package VLSys;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import DBConnection.*;
import java.sql.*;

import javax.swing.table.DefaultTableModel;

import VLSObjects.*;

public class ManagementUserEdit extends JPanel{
    
    JTextField username;
    JTextField userID;
    JPasswordField passwordOld;
    JPasswordField passwordNew;
    JPasswordField passwordConfirm;
    JTextField surname;
    JTextField firstname;
    JComboBox designation;
    
    JButton submitButton;
    JButton cancelButton;
    JButton editUserButton;
    JButton deleteUserButton;
    JButton passwordSubmit;
    JButton passwordCancelButton;
    JButton passwordEditButton;
    
    JLabel usernameLabel;
    JLabel passwordOldLabel;
    JLabel passwordNewLabel;
    JLabel passwordConfirmLabel;
    JLabel surnameLabel;
    JLabel firstnameLabel;    
    JLabel designationLabel;
    JLabel addUserLabel;
    JLabel userIDLabel;
    JScrollPane userScroll;
    JTable userTable;
    
    JTextField filter;
    JLabel filterLabel;
    
    String oldPass, newPass, confirmPass;
    /*
    ImageIcon ask = new ImageIcon("images/prompt_ask.png");
    ImageIcon notice = new ImageIcon("images/prompt_notice.png");
    */
    
    ImageIcon notice_green = new ImageIcon("images/prompt_notice_green.png");
    ImageIcon ask_red = new ImageIcon("images/prompt_ask_red.png");
    ImageIcon notice_red = new ImageIcon("images/prompt_notice_red.png");
    
    DefaultTableModel model;
    
    int x = -1;
    int enable;
    
    //int enable = 1;
    
    Object headers[] = {"User ID", "Username", "Surname", "Firstname", "Designation"};

    
    String blank = "";
    String[] designationChoices = { "", "Cashier", "Manager"};
    String string[] = new String[5];
    
    
    public ManagementUserEdit(final JFrame frame)
    {
        
        setVisible(false);
        setLayout(null);
        setBackground(null);
        
        filterLabel = new JLabel("Search:");
        filterLabel.setBounds(394,390,150,20);
        
        filter = new JTextField();
        filter.setBounds(439,390,150,20);
        filter.setBorder(null);
        
        userID = new JTextField();
        username = new JTextField();
        passwordOld = new JPasswordField();
        passwordNew = new JPasswordField();
        passwordOld = new JPasswordField();
        passwordConfirm = new JPasswordField();
        surname = new JTextField();
        firstname = new JTextField();
        designation = new JComboBox(designationChoices);
        
        userIDLabel = new JLabel("User ID:");
        usernameLabel = new JLabel("Username:");
        passwordOldLabel = new JLabel("Old Password:");
        passwordNewLabel = new JLabel("New Password:");
        passwordConfirmLabel = new JLabel("Confirm New Password:");
        surnameLabel = new JLabel ("Surname:");
        firstnameLabel = new JLabel ("First Name:");
        designationLabel = new JLabel("Designation:");
        addUserLabel = new JLabel("EDIT USER");
        
        submitButton = new JButton();
        cancelButton = new JButton();
        editUserButton = new JButton();
        deleteUserButton = new JButton();
        passwordEditButton = new JButton();
        passwordSubmit = new JButton();
        passwordCancelButton = new JButton();
        
        
        addUserLabel.setFont(new Font("sansserif", Font.PLAIN, 40));
        
        addUserLabel.setBounds(10,10,300,30);
        userIDLabel.setBounds(75, 50, 150, 20);
        usernameLabel.setBounds(57,75,150,20);
        passwordOldLabel.setBounds(380,50,150, 20);
        passwordNewLabel.setBounds(380,100,150,20);
        passwordConfirmLabel.setBounds(380,150,150,20);
        surnameLabel.setBounds(60,100,150,20);
        firstnameLabel.setBounds(58,125,150,20);
        designationLabel.setBounds(49,150,150,20);
        
        
        userID.setBounds(130,50,200,20);
        username.setBounds(130,75,200,20);
        passwordOld.setBounds(380,75,200,20);
        passwordNew.setBounds(380,125,200,20);
        passwordConfirm.setBounds(380,175,200,20);
        surname.setBounds(130,100,200,20);
        firstname.setBounds(130,125,200,20);
        designation.setBounds(130,150,200,20);
        
        userID.setBorder(null);
        username.setBorder(null);
        passwordOld.setBorder(null);
        passwordNew.setBorder(null);
        passwordOld.setBorder(null);
        passwordConfirm.setBorder(null);
        surname.setBorder(null);
        firstname.setBorder(null);
        designation.setBorder(null);
        
        
        submitButton.setText("Submit");
        cancelButton.setText("Clear");
        editUserButton.setText("Edit Details"); 
        deleteUserButton.setText("Delete");
        passwordEditButton.setText("Edit Password");
        passwordSubmit.setText("Submit");
        passwordCancelButton.setText("Cancel");
        
        submitButton.setBounds(180, 175, 75, 20);
        cancelButton.setBounds(255,175,75,20);
        editUserButton.setBounds(15, 390, 100, 20);
        deleteUserButton.setBounds(235, 390, 75, 20);
        passwordEditButton.setBounds(115, 390, 120, 20); 
        passwordSubmit.setBounds(425, 200, 75, 20);
        passwordCancelButton.setBounds(505, 200, 75, 20);
        
        //table codes
        
    
        userTable = new JTable();
        userTable.setModel(new javax.swing.table.DefaultTableModel(null, headers
        ) {


            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
            }
        });
        userScroll = new JScrollPane();
        userTable.getTableHeader().setReorderingAllowed(false);
        
        
        model = (DefaultTableModel)userTable.getModel();
        
        userScroll.setViewportView(userTable);
        userScroll.setBounds(15,240,575,150);
        
        disableButton();
        
        add(userID);
        add(username);
        add(passwordOld);
        add(passwordNew);
        add(passwordConfirm);
        add(designation);
        add(surname);
        add(firstname);
        add(submitButton);
        add(cancelButton);
        add(editUserButton);
        add(passwordEditButton);
        add(passwordSubmit);
        add(passwordCancelButton);
        add(userIDLabel);
        add(usernameLabel);
        add(passwordOldLabel);
        add(passwordNewLabel);
        add(passwordConfirmLabel);
        add(surnameLabel);
        add(firstnameLabel);
        add(designationLabel);
        add(addUserLabel);
        add(userScroll);
        add(deleteUserButton);
        add(filter);
        add(filterLabel);
        
        populateTable("SELECT * FROM userlist ORDER BY userID");
        
         filter.addKeyListener(new KeyAdapter() {
          public void keyReleased(KeyEvent e) {
              
          populateTable("SELECT * FROM userlist WHERE username LIKE '" + filter.getText() + "%' ORDER BY username ASC");
          
          }

          public void keyTyped(KeyEvent e) {
          }

          public void keyPressed(KeyEvent e) {
          }
        });
        
        surname.addKeyListener(new KeyAdapter() {
          public void keyReleased(KeyEvent e) {
              if (e.getKeyCode()==39 || e.getKeyCode()==37)
        {
               
        }
              else 
                surname.setText(capitalizeFirstLetters(surname.getText()));
     
          }

          public void keyTyped(KeyEvent e) {
              
          }

          public void keyPressed(KeyEvent e) {
              
          }
        });
        
        firstname.addKeyListener(new KeyAdapter() {
          public void keyReleased(KeyEvent e) {
              if (e.getKeyCode()==39 || e.getKeyCode()==37)
        {
               
        }
              else 
                firstname.setText(capitalizeFirstLetters(firstname.getText()));
     
          }

          public void keyTyped(KeyEvent e) {
              
          }

          public void keyPressed(KeyEvent e) {
              
          }
        });
        
        userTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TableMouseClicked(evt);
            }
            });
        
       editUserButton.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {
                if(x != -1)
                    enableButton();
                else
                    JOptionPane.showMessageDialog(frame,
                                        "Please Select User to Edit",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);
                
                
            }
        }
        );
       
       deleteUserButton.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {
                    userManager newUm = new userManager();
                    boolean result = false;
                    int n = 20;
                    
                if(x != -1)
                {
                    n = JOptionPane.showConfirmDialog(
                            frame,
                            "Are You Sure",
                            "Vehicle Logging Service",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            ask_red);
                    if(n==0)
                    {
                        result = newUm.deleteUser(username.getText());
                               if (result == true)
                                    JOptionPane.showMessageDialog(frame,
                                            "User Deleted!",
                                            "Vehicle Logging Service",
                                            JOptionPane.WARNING_MESSAGE,
                                            notice_red);
                               model.setRowCount(0);
                               populateTable("SELECT * FROM userlist ORDER BY userID");
                    }
                }    
                else
                    JOptionPane.showMessageDialog(frame,
                                        "Please Select User to Delete",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);
                
                
            }
        }
        );
        
        submitButton.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {

                string[0] = username.getText(); 
                string[1] = new String(passwordNew.getPassword());
                string[2] = new String(passwordConfirm.getPassword());
                string[3] =(String)designation.getSelectedItem();
                
                if(string[0].length() == 0 && string[3] == blank)
                {
                    checkEmpty();
                    JOptionPane.showMessageDialog(frame,
                                        "Incomplete Input",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);
                    
                } 
                else if(string[0].length() == 0 || string[3] == blank )
                {
                    checkEmpty();
                       if(string[3] != blank)
                                
                                if(string[0].length() == 0 && string[1].length() == 0 && string[2].length() == 0)
                                JOptionPane.showMessageDialog(frame,
                                            "Incomplete Input",
                                            "Vehicle Logging Service",
                                            JOptionPane.WARNING_MESSAGE,
                                            notice_red);
                           
                                
                                else if(username.getText().length() < 6 || username.getText().length() > 10)
                                {
                                    JOptionPane.showMessageDialog(frame,
                                                        "Invalid and Incomplete Input",
                                                        "Vehicle Logging Service",
                                                        JOptionPane.WARNING_MESSAGE,
                                                        notice_red);
                                }
                                        
                        else if(username.getText().length() < 6 || username.getText().length() > 10)
                        {
                            JOptionPane.showMessageDialog(frame,
                                                "Invalid and Incomplete Input",
                                                "Vehicle Logging Service",
                                                JOptionPane.WARNING_MESSAGE,
                                                notice_red);

                        }  
                        else
                            JOptionPane.showMessageDialog(frame,
                                            "Incomplete Input",
                                            "Vehicle Logging Service",
                                            JOptionPane.WARNING_MESSAGE,
                                            notice_red);
                     
                     
                    
                }   
                else if(username.getText().length() < 6 || username.getText().length() > 10 || string[3].length() > 10)
                {
                    checkEmpty();
                    JOptionPane.showMessageDialog(frame,
                                        "Invalid Input",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);

                     
                }            
                else if(username.getText().length() >= 6 && username.getText().length() <= 10 && string[4] != blank)   
                {
                    int n = JOptionPane.showConfirmDialog(
                            frame,
                            "Proceed with current values?",
                            "Vehicle Logging Service",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            ask_red);

                    if(n==0)
                    {
                        User editUser = new User();
                        userManager newUm = new userManager();

                        editUser.setUserID(userID.getText());
                        editUser.setUsername(string[0]);
                        editUser.setSurname(surname.getText());
                        editUser.setFirstName(firstname.getText());
                        editUser.setDesignation(string[3]);
                        
                        
                       boolean existing = newUm.user_exist(string[0], userID.getText());
                       //check if a similar record already exists
                           
                       if(existing == true) 
                           {    JOptionPane.showMessageDialog(frame,
                                            "User record already exists!",
                                            "Vehicle Logging Service",
                                            JOptionPane.WARNING_MESSAGE,
                                            notice_red);
                           }
                           else
                           {   //add to database if no similar record is found
                               boolean result = newUm.editUser(editUser);
                               model.setRowCount(0);
                               populateTable("SELECT * FROM userlist ORDER BY userID");
                               if (result == true)
                                    JOptionPane.showMessageDialog(frame,
                                            "User Edited!",
                                            "Vehicle Logging Service",
                                            JOptionPane.WARNING_MESSAGE,
                                            notice_green);
                         }
                       resetValues();
                       x = -1;
                    }
                    
                    
                }
                
            }
        }
        );
        
        cancelButton.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {
                 int n = JOptionPane.showConfirmDialog(
                            frame,
                            "Are you sure you want to clear the values?",
                            "Vehicle Logging Service",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            ask_red);
               if(n==0)
                    { 

                        resetValues();
                        disableButton();
                        x=-1;
                
                    }
               
            }
        }
        );
        
        passwordEditButton.addActionListener(new ActionListener()
        {
           public void actionPerformed(ActionEvent e)
           {    
               
               if(x != -1)
                    enablePasswordFields();
                else
                    JOptionPane.showMessageDialog(frame,
                                        "Please Select User to Edit",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);
               
           }
        }      
         );
        
        passwordSubmit.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {   //System.out.print("Submit clicked");
                oldPass = new String(passwordOld.getPassword());
                newPass = new String(passwordNew.getPassword());
                confirmPass = new String(passwordConfirm.getPassword());
                /*
                 * include error checking here
                 * 
                 */
                System.out.print(" " + newPass.equals(confirmPass) + " ");
                
                if ( (newPass.equals(confirmPass) == false) || newPass.length() < 6 || newPass.length() > 10 || confirmPass.length() > 6 || confirmPass.length() > 10 || oldPass.length() < 6 || oldPass.length()> 10)
                    {   JOptionPane.showMessageDialog(frame,
                                                "Invalid Input.",
                                                "Vehicle Logging Service",
                                                JOptionPane.WARNING_MESSAGE,
                                                notice_red);
                    }
                else
                    {   System.out.print(" " + oldPass + " " + newPass + " " + confirmPass + " i'm here too ");
                
                        userManager editPassword = new userManager();
                        editPassword.editPassword(oldPass, newPass, (String)userID.getText());

                        resetValues();
                        disablePasswordFields();
                    }
                
            }
        }
        );
        
        passwordCancelButton.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {
                 int n = JOptionPane.showConfirmDialog(
                            frame,
                            "Are you sure you want to Cancel?",
                            "Vehicle Logging Service",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            ask_red);
                if(n==0)
                    { 

                        resetValues();
                        disableButton();
                
                    }
               
            }
        }
        );
        
    }
    
        public void disableButton()
        {
            userID.setEnabled(false);
            userID.setEditable(false);
            username.setEnabled(false);
            surname.setEnabled(false);
            firstname.setEnabled(false);
            designation.setEnabled(false);
            cancelButton.setEnabled(false);
            submitButton.setEnabled(false);
            passwordEditButton.setEnabled(true);
            editUserButton.setEnabled(true);
            deleteUserButton.setEnabled(true);
            enable = 1;
        }
        
        public void resetValues()
        {
                    username.setBackground(null);
                    surname.setBackground(null);
                    firstname.setBackground(null);
                    designation.setBackground(null);
                    username.setText("");
                    passwordNew.setText("");
                    passwordConfirm.setText("");
                    surname.setText("");
                    firstname.setText("");
                    designation.setSelectedItem("");
                    disableButton();
                    disablePasswordFields();
                    resetPasswordValues();
                    x = -1;

        }
        
        private void enableButton()
        {
                username.setEnabled(true);
                surname.setEnabled(true);
                firstname.setEnabled(true);
                designation.setEnabled(true);
                submitButton.setEnabled(true);
                cancelButton.setEnabled(true);
                editUserButton.setEnabled(false);
                deleteUserButton.setEnabled(false);
                passwordEditButton.setEnabled(false);
                enable = 0;
        }
        
        private void enablePasswordFields()
        {    passwordOld.setEnabled(true);
             passwordNew.setEnabled(true);
             passwordConfirm.setEnabled(true);
             passwordSubmit.setEnabled(true);
             passwordCancelButton.setEnabled(true);
             editUserButton.setEnabled(false);
             deleteUserButton.setEnabled(false);
             passwordEditButton.setEnabled(false);
            
        }
        public void disablePasswordFields()
        {
            passwordOld.setEnabled(false);
            passwordNew.setEnabled(false);
            passwordConfirm.setEnabled(false);
            passwordSubmit.setEnabled(false);
            passwordCancelButton.setEnabled(false);
            passwordEditButton.setEnabled(true);
            
        }
        
        public void resetPasswordValues()
        {
             passwordNew.setBackground(null);
             passwordConfirm.setBackground(null);
             passwordOld.setBackground(null);
             passwordNew.setText("");
             passwordConfirm.setText("");
             passwordOld.setText("");
        }
        
        public void checkEmpty()
    {   
        String s = "";
        String c = new String(passwordNew.getPassword());
        String c1 = new String(passwordConfirm.getPassword());
       
        if(username.getText().length() == 0)
            username.setBackground(Color.YELLOW);
               
        else if(username.getText().length() < 6 || username.getText().length() > 10)
            username.setBackground(Color.RED);
                 
        if( username.getText().length() >= 6 && username.getText().length() <= 10)
            username.setBackground(null);
        
        
        if( c.length() == 0)
            passwordNew.setBackground(Color.YELLOW);
        
        else if(c.length() < 6 || c.length() > 10)
            passwordNew.setBackground(Color.RED);
        
        if( c.length() >= 6 && c.length() <= 10)
            passwordNew.setBackground(null);
        
        if( c1.length() == 0)
            passwordConfirm.setBackground(Color.YELLOW);
        
        else if(c1.length() < 6 || c1.length() > 10)
            passwordConfirm.setBackground(Color.RED);
        
        if( c1.length() >= 6 && c1.length() <= 10)
            passwordConfirm.setBackground(null);
        
        if(surname.getText().length() == 0)
            surname.setBackground(Color.YELLOW);
               
        else if(surname.getText().length() < 1 || surname.getText().length() > 45)
            surname.setBackground(Color.RED);
                 
        if( surname.getText().length() >= 1 && surname.getText().length() <= 45)
            surname.setBackground(null);
        
        if(surname.getText().length() == 0)
            surname.setBackground(Color.YELLOW);
               
        else if(firstname.getText().length() < 1 || firstname.getText().length() > 45)
            firstname.setBackground(Color.RED);
                 
        if( firstname.getText().length() >= 1 && firstname.getText().length() <= 45)
            firstname.setBackground(null);
        
        if((String)designation.getSelectedItem() == s)
            designation.setBackground(Color.YELLOW);
                
        if((String)designation.getSelectedItem() != s)
            designation.setBackground(null);
        
    }
        
        
        
        private void TableMouseClicked(java.awt.event.MouseEvent evt) 
           {                                     
               int rowSelected = userTable.getSelectedRow();
               
               if(enable == 1)
               {
                   x = rowSelected;
               int uID = (Integer)model.getValueAt(x, 0);
                   
               
               userID.setText(Integer.toString(uID));
               username.setText((String)model.getValueAt(x, 1));
               surname.setText((String)model.getValueAt(x, 2));
               firstname.setText((String)model.getValueAt(x, 3));
               designation.setSelectedItem((String)model.getValueAt(x, 4));
               }

            }
        
          public void populateTable(String pS){
         
              try{
                    //opens db connection
                    ConnectionFactory myFactory = ConnectionFactory.getFactory();
                    Connection conn = myFactory.getConnection();

                    //SQL Query
                    PreparedStatement pstmt = conn.prepareStatement(pS);

                    //execute query
                    ResultSet rs = pstmt.executeQuery();
                    
                    model.getDataVector().removeAllElements();
                    userTable.setAutoCreateRowSorter(true);

                    //populate JTable 
                    while(rs.next()){
                    model.addRow(new Object[]{rs.getInt(1), rs.getString(2), rs.getString(4), rs.getString(5), rs.getString(6)});
                    
                    model.fireTableDataChanged();
                    }
                    
                    //close DB connection
                    conn.close();
                }
                      
                catch(SQLException e)
                {
                   e.printStackTrace();
                   System.out.print("ayaw!");
                }
             
          }
          
        public static String capitalizeFirstLetters ( String s ) {

        for (int i = 0; i < s.length(); i++) {

            if (i == 0) {
                // Capitalize the first letter of the string.
                s = String.format( "%s%s",
                             Character.toUpperCase(s.charAt(0)),
                             s.substring(1) );
            }

            // Is this character a non-letter or non-digit?  If so
            // then this is probably a word boundary so let's capitalize
            // the next character in the sequence.
            if (!Character.isLetterOrDigit(s.charAt(i))) {
                if (i + 1 < s.length()) {
                    s = String.format( "%s%s%s",
                                 s.subSequence(0, i+1),
                                 Character.toUpperCase(s.charAt(i + 1)),
                                 s.substring(i+2) );
                }
            }

        }

        return s;
          }
    
}
